import React, { FormEventHandler } from 'react';
import { Controller, SubmitHandler, useForm } from 'react-hook-form';

import { getUserCards } from '@/entities/profile/model/selectors';
import { ModalContext } from '@/shared/context/ModalContext';
import { getPaymentSystem } from '@/shared/lib/getCardSystem';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, SecondInput, Snackbar, Title } from '@/shared/ui';
import { ModalPage } from '@/widgets/ModalPage';
import { useSnackbar } from 'notistack';

import { addPaymentCard } from '../../../../entities/profile/model/actions';
import cs from './AddPaymentCard.module.scss';

interface IPaymentCardForm {
  number: number;
  expDate: string;
}

export const AddPaymentCard = () => {
  const { closeModal } = React.useContext(ModalContext);
  const { enqueueSnackbar } = useSnackbar();
  const dispatch = useAppDispatch();

  const cards = useAppSelector(getUserCards);

  const { register, control, setValue, watch, handleSubmit } = useForm<IPaymentCardForm>();

  const onSubmit: SubmitHandler<IPaymentCardForm> = (data) => {
    if (cards.some((card) => card.number === data.number)) {
      enqueueSnackbar('Карта уже добавлена', {
        variant: 'error',
        content: (key, message) => <Snackbar id={key} message={message} size="md" variant="error" />,
      });
      return;
    }
    const system = getPaymentSystem(String(data.number));
    dispatch(addPaymentCard({ number: data.number, system }));
    closeModal();
    enqueueSnackbar('Карта добавлена', {
      variant: 'success',
      content: (key, message) => <Snackbar id={key} message={message} size="md" variant="success" />,
    });
  };
  const clearField = (field: keyof IPaymentCardForm) => {
    setValue(field, '', { shouldDirty: false });
  };

  return (
    <ModalPage handleClose={() => closeModal()} isOpen>
      <div className={cs.modal}>
        <Title className={cs.title} size="modal-size">
          Добавить карту
        </Title>
        <form onSubmit={handleSubmit(onSubmit)}>
          <Controller
            control={control}
            name="number"
            render={({ field }) => (
              <SecondInput
                clearing={() => {}}
                data-testid="number-input"
                guide={false}
                inputMode="numeric"
                label="Номер карты"
                mask={[
                  /\d/,
                  /\d/,
                  /\d/,
                  /\d/,
                  ' ',
                  /\d/,
                  /\d/,
                  /\d/,
                  /\d/,
                  ' ',
                  /\d/,
                  /\d/,
                  /\d/,
                  /\d/,
                  ' ',
                  /\d/,
                  /\d/,
                  /\d/,
                  /\d/,
                ]}
                onRightClick={() => clearField('number')}
                register={register}
                right={watch('number')?.toString().length > 0 && 'clear'}
                {...field}
              />
            )}
          />
          <Controller
            control={control}
            name="expDate"
            render={({ field }) => (
              <SecondInput
                className={cs.input}
                clearing={() => {}}
                {...field}
                data-testid="expDate-input"
                guide={false}
                inputMode="numeric"
                label="Срок действия"
                mask={[/\d/, /\d/, '/', /\d/, /\d/]}
                onRightClick={() => clearField('expDate')}
                placeholder="ДД/ГГ"
                register={register}
                right={watch('expDate')?.toString().length > 0 && 'clear'}
              />
            )}
          />
          <Button type="submit" variant={ButtonVariants.Primary}>
            Добавить
          </Button>
        </form>
      </div>
    </ModalPage>
  );
};
